const db = require("./database.js")

async function selectCartListByUserId(user_id) {
  return new Promise((resolve, reject) => {
    db.all('select c.cart_id, p.prod_id, p.title, p.info, p.img, p.n_price, p.o_price, c.amount from cart c left join prod p on c.prod_id = p.prod_id where c.user_id = ?', [user_id], (err, rows) => {
      if (err) {
        reject(err);
      } else {
        resolve(rows)
      }
    })
  })
}

async function selectCartByUserIdAndProdId(user_id, prod_id) {
  return new Promise((resolve, reject) => {
    db.all('select * from cart where user_id = ? and prod_id = ?', [user_id, prod_id], (err, rows) => {
      if (err) {
        reject(err);
      } else if (rows == null || rows.length == 0) {
        resolve(null)
      } else {
        resolve(rows[0])
      }
    })
  })
}

async function updateCartAmount(cart_id, amount) {
  return new Promise((resolve, reject) => {
    db.run('update cart set amount = ? where cart_id = ?', [amount, cart_id], (err, result) => {
      if (err) {
        reject(err);
      } else {
        resolve(result)
      }
    })
  })
}

async function insertCart(cart) {
  return new Promise((resolve, reject) => {
    db.run('insert into cart (user_id, prod_id, amount) values (?,?,?)', [cart.user_id, cart.prod_id, cart.amount], (err, result) => {
      if (err) {
        reject(err);
      } else {
        resolve(result)
      }
    })
  })
}

async function deleteCart(cart_id) {
  return new Promise((resolve, reject) => {
    db.run('delete from cart where cart_id = ?', [cart_id], (err, result) => {
      if (err) {
        reject(err);
      } else {
        resolve(result)
      }
    })
  })
}

async function selectCartByCartIdArray(ids) {
  return new Promise((resolve, reject) => {
    var sql = 'select c.cart_id, c.user_id, c.prod_id, c.amount, p.n_price from cart c left join prod p on c.prod_id = p.prod_id where c.cart_id in (' + ids.join(',') + ')'
    db.all(sql, [], (err, rows) => {
      if (err) {
        reject(err)
      } else {
        resolve(rows)
      }
    })
  })
}

module.exports = {
  selectCartListByUserId,
  selectCartByUserIdAndProdId,
  updateCartAmount,
  insertCart,
  deleteCart,
  selectCartByCartIdArray
}
